import { api } from './api'
import type { ApiResponse, PaginatedResponse, PaginationParams } from '../types'

interface User {
  id: number
  username: string
  email: string
  role: string
  avatar?: string
  createdAt: string
  updatedAt: string
}

interface UpdateUserRequest {
  username?: string
  email?: string
  password?: string
  avatar?: string
}

interface UpdatePasswordRequest {
  oldPassword: string
  newPassword: string
}

export const usersApi = api.injectEndpoints({
  endpoints: (builder) => ({
    getUsers: builder.query<ApiResponse<PaginatedResponse<User>>, PaginationParams>({
      query: (params) => ({
        url: '/users',
        params,
      }),
      providesTags: (result) =>
        result
          ? [
              ...result.data.content.map(({ id }) => ({ type: 'User' as const, id })),
              { type: 'User' as const, id: 'LIST' },
            ]
          : [{ type: 'User' as const, id: 'LIST' }],
    }),

    getUser: builder.query<ApiResponse<User>, number>({
      query: (id) => `/users/${id}`,
      providesTags: (result) =>
        result ? [{ type: 'User' as const, id: result.data.id }] : [],
    }),

    updateUser: builder.mutation<ApiResponse<User>, { id: number; data: UpdateUserRequest }>({
      query: ({ id, data }) => ({
        url: `/users/${id}`,
        method: 'PUT',
        body: data,
      }),
      invalidatesTags: (result) =>
        result ? [{ type: 'User', id: result.data.id }] : [],
    }),

    deleteUser: builder.mutation<ApiResponse<void>, number>({
      query: (id) => ({
        url: `/users/${id}`,
        method: 'DELETE',
      }),
      invalidatesTags: [{ type: 'User', id: 'LIST' }],
    }),

    updatePassword: builder.mutation<ApiResponse<void>, UpdatePasswordRequest>({
      query: (data) => ({
        url: '/users/password',
        method: 'PUT',
        body: data,
      }),
    }),

    updateAvatar: builder.mutation<ApiResponse<{ avatar: string }>, FormData>({
      query: (data) => ({
        url: '/users/avatar',
        method: 'POST',
        body: data,
      }),
      invalidatesTags: ['User'],
    }),
  }),
})

export const {
  useGetUsersQuery,
  useGetUserQuery,
  useUpdateUserMutation,
  useDeleteUserMutation,
  useUpdatePasswordMutation,
  useUpdateAvatarMutation,
} = usersApi 